//
//  DeviceSettingViewController.m
//  BMS
//
//  Created by 颜魏 on 2021/4/26.
//

#import "DeviceSettingViewController.h"
#import "ChooseDeviceModeTableViewCell.h"
#import "FunctionOnOffTableViewCell.h"
#import "EditTableViewCell.h"
#import "ChooseBatteryTypeTableViewCell.h"
#import "SafetySettingTableViewCell.h"
#import "ProgressHUD.h"
#import "BTManager.h"
#import "ShortProtectionTableViewCell.h"

#define Localized(key)  NSLocalizedString((key), nil)

@interface DeviceSettingViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, assign) NSInteger queryOrder;     //查询指令
@property (nonatomic, strong) NSMutableDictionary   *dataDictionary;
@property (nonatomic, strong) NSArray   *sectionArray;
@property (nonatomic, strong) NSMutableArray   *isExpandArray;
@property (nonatomic, strong) NSTimer   *getSettingTimer;
@property (nonatomic, assign) BOOL isReadSafteyData;
@property (nonatomic, assign) BOOL userIsEditing;
@property (nonatomic, strong) NSMutableArray   *quryResultStatus;
@property (nonatomic, assign) BOOL  isCurrentPage;

@end

@implementation DeviceSettingViewController
{
    int SafetySetting[13][5];
    CGFloat batteryCapacity;
    int loopCount;
    int fillTime;
    int resistanceCount,resistanceValue;//采样电阻
    int preChargeDischargeTime;//预充时间
    int serialCount;//串数
    int sleepMode;//休眠功能状态
    int balanceMode;//均衡功能
    int heatMode;//加热功能
    int coolMode;//冷凝功能
    int startSendOneFrame;
    int totalSendFrame;
    Byte upload_array[1024+9];
    int mosRelayMode;
    int chargeRefrenceCurrent,dischargeRefenceCurrent,chargeShortCurrent,dischargeShortCurrent; //充电参考电流，放电参考电流,充电短路电流，放电短路电流
    int onetimePassword,permanentPassword,shortReserve,shortReserve2;//一次性密码，永久密码，保留
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = NSLocalizedString(@"Parameter setting", nil);
    self.userIsEditing = NO;
    self.quryResultStatus = [[NSMutableArray alloc] initWithArray:@[@0, @0, @0, @0, @0, @0, @0, @0]];
        
    WeakSelf
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        weakSelf.userIsEditing = YES;
    }];
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.userIsEditing = NO;
        });
    }];

    self.dataDictionary = [[NSMutableDictionary alloc]init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(turnOffDevices) name:kBTDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didUpdateData:) name:kBTDidReciveData object:nil];
    
    UINib *nibChooseMode = [UINib nibWithNibName:@"ChooseDeviceModeTableViewCell"
                                    bundle: [NSBundle mainBundle]];
    UINib *nibFunc = [UINib nibWithNibName:@"FunctionOnOffTableViewCell"
                                    bundle: [NSBundle mainBundle]];
    UINib *nibEdit = [UINib nibWithNibName:@"EditTableViewCell"
                                    bundle: [NSBundle mainBundle]];
    UINib *nibChooseBattery = [UINib nibWithNibName:@"ChooseBatteryTypeTableViewCell"
                                    bundle: [NSBundle mainBundle]];
    UINib *nibChooseSafety = [UINib nibWithNibName:@"SafetySettingTableViewCell"
                                             bundle: [NSBundle mainBundle]];
    UINib *nibShort = [UINib nibWithNibName:@"ShortProtectionTableViewCell"
                                             bundle: [NSBundle mainBundle]];
    [self.tableView registerNib:nibChooseMode forCellReuseIdentifier:@"ChooseDeviceModeTableViewCell"];
    [self.tableView registerNib:nibFunc forCellReuseIdentifier:@"FunctionOnOffTableViewCell"];
    [self.tableView registerNib:nibEdit forCellReuseIdentifier:@"EditTableViewCell"];
    [self.tableView registerNib:nibChooseBattery forCellReuseIdentifier:@"ChooseBatteryTypeTableViewCell"];
    [self.tableView registerNib:nibChooseSafety forCellReuseIdentifier:@"SafetySettingTableViewCell"];
    [self.tableView registerNib:nibShort forCellReuseIdentifier:@"ShortProtectionTableViewCell"];
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    
    self.sectionArray = [NSArray arrayWithObjects:
                         NSLocalizedString(@"Basic setting", nil),
                         NSLocalizedString(@"Sleep function", nil),
                         NSLocalizedString(@"Heating function", nil),
                         NSLocalizedString(@"Cooling function", nil),
                         NSLocalizedString(@"Balancing function", nil),
                         NSLocalizedString(@"OV_Cell", nil),
                         NSLocalizedString(@"UV_Cell", nil),
                         NSLocalizedString(@"OV_Bat", nil),
                         NSLocalizedString(@"UV_Bat", nil),
                         NSLocalizedString(@"OC_CHG", nil),
                         NSLocalizedString(@"OC_DSG", nil),
                         NSLocalizedString(@"OT_CHG", nil),
                         NSLocalizedString(@"UT_CHG", nil),
                         NSLocalizedString(@"OT_DSG", nil),
                         NSLocalizedString(@"UT_DSG", nil),
                         NSLocalizedString(@"OT_MOS", nil),
                         NSLocalizedString(@"Voltage difference is too large", nil),
                         NSLocalizedString(@"Low SOC", nil),
                         NSLocalizedString(@"Short Protection Para", nil), nil];
    
    self.isExpandArray = [[NSMutableArray alloc]init];
    for (NSInteger i = 0; i < self.sectionArray.count; i++) {
        [self.isExpandArray addObject:@"0"];//0:没展开 1:展开
    }
    [ProgressHUD showActivityMessageInWindow:NSLocalizedString(@"Retrieve setting...", nil) timer:3];
    self.queryOrder = 0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ProgressHUD hideHUD];
    });
    self.getSettingTimer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        {
//            BOOL haveEnd = YES;
//            for (NSNumber *num in weakSelf.quryResultStatus) {
//                if (num.integerValue == 0) {
//                    haveEnd = NO;
//                }
//            }
//            if (haveEnd) {
//                return;
//            }
            if (!weakSelf.isCurrentPage) {
                return;
            }
//            NSLog(@"queryOrder===================%ld", weakSelf.queryOrder);
            switch (weakSelf.queryOrder) {
                case 0:
                {
                    [weakSelf queryBasicInfo];//4.6 系统基础参数读取
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 0) {
//                            weakSelf.queryOrder = 1;
//                        }
//                    });
                }
                    break;
                case 1:
                {
                    [weakSelf queryBatteryAndOtherInfo]; //3.4 主控读取电池其他信息
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 1) {
//                            weakSelf.queryOrder = 2;
//                        }
//                    });
                }
                    break;
                case 2:
                {
                    [weakSelf querySoc];//4.5 SOC参数读取
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 2) {
//                            weakSelf.queryOrder = 3;
//                        }
//                    });
                }
                    break;
                case 3:
                {
                    [weakSelf querySaftey]; //4.1 保护参数读取
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 3) {
//                            weakSelf.queryOrder = 4;
//                        }
//                    });
                }
                    break;
                case 4:
                {
                    [weakSelf queryHeatAndCool]; //4.7 加热&冷凝参数读取
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 4) {
//                            weakSelf.queryOrder = 5;
//                        }
//                    });
                }
                    break;
                case 5:
                {
                    [weakSelf querySleepInfo]; //4.4 休眠参数读取
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 5) {
//                            weakSelf.queryOrder = 6;
//                        }
//                    });
                }
                    break;
                case 6:
                {
                    [weakSelf queryBalanceInfo]; //4.2 均衡参数读取
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 6) {
//                            weakSelf.queryOrder = 7;
//                        }
//                    });
                }
                    break;
                case 7:
                {
                    [weakSelf queryProtection]; //4.3 保护参数
                    weakSelf.queryOrder++;
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        if (weakSelf.queryOrder == 7) {
//                            weakSelf.queryOrder = 0;
//                        }
//                    });
                }
                    break;
                default:
                    weakSelf.queryOrder = 0;
                    break;
            }
            if (weakSelf.queryOrder>3) {
                [ProgressHUD hideHUD];
            }
        }
    }];
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.getSettingTimer invalidate];
    self.getSettingTimer=nil;
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"SettingPageState" object:@(0)];
    [[NSNotificationCenter defaultCenter] removeObserver:@"didUpdateData"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"turnOffDevices"];
    self.isCurrentPage = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"SettingPageState" object:@(1)];
    self.isCurrentPage = YES;
}

- (IBAction)actionRefresh:(id)sender {
    [self refresh];
}

- (void)turnOffDevices {
    //蓝牙断开
}

-(void)refresh {
//    [self clearData];
//    self.isReadSafteyData = false;
//    [self.tableView reloadData];
    [ProgressHUD showActivityMessageInWindow:NSLocalizedString(@"Retrieve setting...", nil) timer:3];
    self.queryOrder = 0;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 19;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([_isExpandArray[section]isEqualToString:@"1"]) {
        if (section==0)
            return 8;
        return 1;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0)  //基本设置
    {
        return [self getGeneralCell:indexPath];
    }
    if (indexPath.section<5)  //基本设置
    {
        return [self getSwitchCell:indexPath];
    }
    if(indexPath.section==18)
    {
        return [self getShortProtectionCell:indexPath];
    }
    //if (indexPath.section==0)  //安全设置
    {
        return [self getSafteyCell:indexPath];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (![_isExpandArray[indexPath.section]isEqualToString:@"1"]) {
        return 0;
    }
    if (indexPath.section==18) //休眠功能 加热功能 冷凝功能 均衡功能
    {
       return 240;
    }
    if (indexPath.section==0)//基本设置
    {
        if (indexPath.row==0) return 125;
        if (indexPath.row==1) return 50;
        return 40;
    }
    if (indexPath.section<5) //休眠功能 加热功能 冷凝功能 均衡功能
    {
        if(indexPath.section==1) return 290;
        if(indexPath.section==2) return 410;
        if(indexPath.section == 4) return 170;
       return 330;
    }
    return 200;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth - 30, 59)];
    headerView.backgroundColor = RGB16(0xf5f6f7);
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 3, kWidth-30, 53)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [headerView addSubview:bgView];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(18, 0, kWidth-100, 53)];
    titleLabel.text = _sectionArray[section];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = RGB16(0x333333);
    [bgView addSubview:titleLabel];
    
    UIImageView *arrowIV = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth-46, 19, 15, 15)];
    arrowIV.image = [UIImage imageNamed:[_isExpandArray[section] isEqualToString:@"0"] ? @"img39.png" : @"img38.png"];
    [bgView addSubview:arrowIV];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    tap.delegate = self;
    [headerView addGestureRecognizer:tap];
    headerView.tag = section;
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 59;
}

- (void)tapAction:(UITapGestureRecognizer *)tap{

    if ([_isExpandArray[tap.view.tag] isEqualToString:@"0"]) {
        [_isExpandArray replaceObjectAtIndex:tap.view.tag withObject:@"1"];
    }else{
        [_isExpandArray replaceObjectAtIndex:tap.view.tag withObject:@"0"];
        
    }
    [self.tableView reloadData];
//    NSIndexSet *set = [NSIndexSet indexSetWithIndex:tap.view.tag];
//    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}

#pragma 各项CELL参数获取

-(UITableViewCell*) getGeneralCell:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        ChooseDeviceModeTableViewCell *cell =  [self.tableView dequeueReusableCellWithIdentifier:@"ChooseDeviceModeTableViewCell" forIndexPath:indexPath];
        [cell.buttonMosAll setTitle:Localized(@"MOS_Same_Gate") forState:UIControlStateNormal];
        [cell.buttonMosSingle setTitle:Localized(@"MOS_Split_Gate") forState:UIControlStateNormal];
        [cell.buttonRelayAll setTitle:Localized(@"Relay_Same_Gate") forState:UIControlStateNormal];
        [cell.buttonRelaySingle setTitle:Localized(@"Relay_Split_Gate") forState:UIControlStateNormal];
       
        return cell;
    }
   
    
    if (indexPath.row==1)
    {
        ChooseBatteryTypeTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ChooseBatteryTypeTableViewCell" forIndexPath:indexPath];
        [cell.buttonBatteryTernary setTitle:[NSString stringWithFormat:@"%@%@", Localized(@"Battery type:"), Localized(@"Li-ion")] forState:UIControlStateNormal];
        [cell.buttonBatteryPhosphoricacid setTitle:[NSString stringWithFormat:@"%@%@", Localized(@"Battery type:"), Localized(@"lithium iron phosphate")] forState:UIControlStateNormal];
        [cell.mosrelaySwitch removeTarget:self action:@selector(mosrelaySwitchChange:) forControlEvents:(UIControlEvents)UIControlEventValueChanged];
        if (mosRelayMode>0)
        {
            [cell.mosrelaySwitch setOn:true];
        }
        else
        {
            [cell.mosrelaySwitch setOn:false];
        }
        [cell.mosrelaySwitch addTarget:self action:@selector(mosrelaySwitchChange:) forControlEvents:UIControlEventValueChanged];   // 开关事件切换通知
        return cell;
    }
    
    if (indexPath.row==2)//串数
    {
        EditTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"EditTableViewCell" forIndexPath:indexPath];
        cell.titleLabel.text=Localized(@"SeriesNum");
        cell.unitLabel.text=@"";
        cell.valueTextfield.text=[NSString stringWithFormat:@"%i",serialCount];
        cell.syncButton.tag=indexPath.row;
        [cell.syncButton removeTarget:self action:@selector(basicSyncBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell.syncButton addTarget:self action:@selector(basicSyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    if (indexPath.row==3)//电池包容量
    {
        EditTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"EditTableViewCell" forIndexPath:indexPath];
        cell.titleLabel.text=Localized(@"Battery capicity");
        cell.unitLabel.text=@"Ah";
        cell.valueTextfield.text=[NSString stringWithFormat:@"%.1f",batteryCapacity];
        cell.syncButton.tag=indexPath.row;
        [cell.syncButton removeTarget:self action:@selector(basicSyncBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell.syncButton addTarget:self action:@selector(basicSyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    if (indexPath.row==4)//循环次数
    {
        EditTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"EditTableViewCell" forIndexPath:indexPath];
        cell.titleLabel.text=Localized(@"Recycle count");
        cell.unitLabel.text=@"";
        cell.valueTextfield.text=[NSString stringWithFormat:@"%i",loopCount];
        cell.syncButton.tag=indexPath.row;
        [cell.syncButton removeTarget:self action:@selector(basicSyncBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell.syncButton addTarget:self action:@selector(basicSyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    if (indexPath.row==5)//预充时间
    {
        EditTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"EditTableViewCell" forIndexPath:indexPath];
        cell.titleLabel.text=Localized(@"PreCHG_Time");
        cell.unitLabel.text=@"ms";
        cell.valueTextfield.text=[NSString stringWithFormat:@"%i",preChargeDischargeTime];
        cell.syncButton.tag=indexPath.row;
        [cell.syncButton removeTarget:self action:@selector(basicSyncBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell.syncButton addTarget:self action:@selector(basicSyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    if (indexPath.row==6)//采样电阻阻值
    {
        EditTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"EditTableViewCell" forIndexPath:indexPath];
        cell.titleLabel.text=Localized(@"Cs_Res");
        cell.unitLabel.text=@"mΩ";
        cell.valueTextfield.text=[NSString stringWithFormat:@"%i",resistanceValue];
        cell.syncButton.tag=indexPath.row;
        [cell.syncButton removeTarget:self action:@selector(basicSyncBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell.syncButton addTarget:self action:@selector(basicSyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }

    EditTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"EditTableViewCell" forIndexPath:indexPath];
    cell.titleLabel.text=Localized(@"Cs_ResNum");
    cell.unitLabel.text=@"";
    cell.valueTextfield.text=[NSString stringWithFormat:@"%i",resistanceCount];
    cell.syncButton.tag=indexPath.row;
    [cell.syncButton removeTarget:self action:@selector(basicSyncBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.syncButton addTarget:self action:@selector(basicSyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

-(UITableViewCell*) getSwitchCell:(NSIndexPath *)indexPath
{
    FunctionOnOffTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"FunctionOnOffTableViewCell" forIndexPath:indexPath];
    cell.modeSwitch.tag=indexPath.section;
    [cell.modeSwitch addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];   // 开关事件切换通知
    [cell.syncButton addTarget:self action:@selector(FunctionSyncBtn:) forControlEvents:UIControlEventTouchDown];
    cell.syncButton.tag=indexPath.section;
    [cell.valueTextfield8 setHidden:false];
    [cell.titleLabel8 setHidden:false];
    [cell.unitLabel8 setHidden:false];
    [cell.valueTextfield9 setHidden:false];
    [cell.titleLabel9 setHidden:false];
    [cell.unitLabel9 setHidden:false];
    if (indexPath.section==1)
    {

        if (sleepMode>0)
        {
            [cell.modeSwitch setOn:true];
        }
        else
        {
            [cell.modeSwitch setOn:false];
        }
   
        cell.titleLabel.text=Localized(@"Sleep function");//休眠功能
        cell.titleLabel1.text=Localized(@"VNor_sleep"); //正常休眠电压
        cell.titleLabel2.text=Localized(@"TNor_sleep");//正常休眠时间
        cell.titleLabel3.text=Localized(@"V_OD_sleep");//过放休眠电压
        cell.titleLabel4.text=Localized(@"T_OD_sleep");//过放休眠时间
        cell.titleLabel5.text=Localized(@"FilterCCHG");//充电电流过滤
        cell.titleLabel6.text=Localized(@"FilterCDSG");//放电电流过滤
        cell.titleLabel7.text=Localized(@"RTC_WI");
        cell.titleLabel8.text=Localized(@"Reserve");
        
        cell.unitLabel1.text=@"mV";
        cell.unitLabel2.text=NSLocalizedString(@"Min", nil);
        cell.unitLabel3.text=@"mV";
        cell.unitLabel4.text=NSLocalizedString(@"Min", nil);
        cell.unitLabel5.text=@"A";
        cell.unitLabel6.text=@"A";
        cell.unitLabel7.text=NSLocalizedString(@"Min", nil);
        cell.unitLabel8.text=@"";
        cell.unitLabel9.text=@"";
        NSData *data=[self.dataDictionary objectForKey:@"Data4.4"]; //4.4 休眠参数读取
        if (data)
        {
            Byte*data_array=(Byte*)[data bytes];
            cell.valueTextfield1.text=[NSString stringWithFormat:@"%i",data_array[3]*256+data_array[3+1]];
            cell.valueTextfield2.text=[NSString stringWithFormat:@"%i",data_array[3+2]*256+data_array[3+2+1]];
            cell.valueTextfield3.text=[NSString stringWithFormat:@"%i",data_array[3+2*2]*256+data_array[3+2*2+1]];
            cell.valueTextfield4.text=[NSString stringWithFormat:@"%i",data_array[3+3*2]*256+data_array[3+3*2+1]];
            cell.valueTextfield5.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+4*2]*256+data_array[3+4*2+1])/10.0f];
            cell.valueTextfield6.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+5*2]*256+data_array[3+5*2+1])/10.0f];
            cell.valueTextfield7.text=[NSString stringWithFormat:@"%i",data_array[3+6*2]*256+data_array[3+6*2+1]];
            [cell.valueTextfield8 setHidden:true];
            [cell.titleLabel8 setHidden:true];
            [cell.valueTextfield9 setHidden:true];
            [cell.titleLabel9 setHidden:true];
            [cell.unitLabel8 setHidden:true];
            [cell.unitLabel9 setHidden:true];
        }
        return cell;
    }
    if (indexPath.section==2)
    {
 
        if (heatMode>0)
        {
            [cell.modeSwitch setOn:true];
        }
        else
        {
            [cell.modeSwitch setOn:false];
        }
        cell.modeSwitch.tag=indexPath.section;
        [cell.modeSwitch addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];   // 开关事件切换通知
        
        cell.titleLabel.text=Localized(@"Heating function");
        cell.titleLabel1.text=Localized(@"TH_stop_DSG");
        cell.titleLabel2.text=Localized(@"T_allowed_DSG");
        cell.titleLabel3.text=Localized(@"TH_trigger_DSG");
        cell.titleLabel4.text=Localized(@"TH_stop_CHG");
        cell.titleLabel5.text=Localized(@"T_allowed_CHG");
        cell.titleLabel6.text=Localized(@"TH_trigger_CHG");
        cell.titleLabel7.text=Localized(@"HeatCur_Max");
        cell.titleLabel8.text=Localized(@"HeatCur_Min");
        cell.titleLabel9.text=Localized(@"HeatTime");
        cell.titleLabel10.text=Localized(@"Reserve");
        
        cell.unitLabel1.text=@"°C";
        cell.unitLabel2.text=@"°C";
        cell.unitLabel3.text=@"°C";
        cell.unitLabel4.text=@"°C";
        cell.unitLabel5.text=@"°C";
        cell.unitLabel6.text=@"°C";
        cell.unitLabel7.text=@"A";
        cell.unitLabel8.text=@"A";
        cell.unitLabel9.text=NSLocalizedString(@"Min", nil);
        cell.unitLabel10.text=@"";
        
        NSData *data;
        data=[self.dataDictionary objectForKey:@"Data4.7"]; //4.7 加热&冷凝参数读取
        if (data)
        {
            Byte*data_array=(Byte*)[data bytes];
            cell.valueTextfield1.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3]*256+data_array[3+1]-400)/10.0f ] ;
            cell.valueTextfield2.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+2]*256+data_array[3+2+1]-400)/10.0f ];
            cell.valueTextfield3.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+2*2]*256+data_array[3+2*2+1]-400)/10.0f ];
            cell.valueTextfield4.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+3*2]*256+data_array[3+3*2+1]-400)/10.0f ];
            cell.valueTextfield5.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+4*2]*256+data_array[3+4*2+1]-400)/10.0f ];
            cell.valueTextfield6.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+5*2]*256+data_array[3+5*2+1]-400)/10.0f ];
            cell.valueTextfield7.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+6*2]*256+data_array[3+6*2+1])/10.f];
            cell.valueTextfield8.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+7*2]*256+data_array[3+7*2+1])/10.f];
            cell.valueTextfield9.text=[NSString stringWithFormat:@"%i",(data_array[3+8*2]*256+data_array[3+8*2+1])];
        }
        return cell;
    }
    if (indexPath.section==3)
    {
 
        if (coolMode>0)
        {
            [cell.modeSwitch setOn:true];
        }
        else
        {
            [cell.modeSwitch setOn:false];
        }
        cell.titleLabel.text=Localized(@"Cooling function");
        cell.titleLabel1.text=Localized(@"Tc_trigger_DSG");
        cell.titleLabel2.text=Localized(@"Tc_stop_DSG");
        cell.titleLabel3.text=Localized(@"Tc_trigger_CHG");
        cell.titleLabel4.text=Localized(@"Tc_stop_CHG");
        cell.titleLabel5.text=Localized(@"CoolCur_Max");
        cell.titleLabel6.text=Localized(@"CoolCur_Min");
        cell.titleLabel7.text=Localized(@"CoolTime");
        cell.titleLabel8.text=Localized(@"Reserve");
        cell.titleLabel9.text=@"";

        cell.unitLabel1.text=@"℃";
        cell.unitLabel2.text=@"℃";
        cell.unitLabel3.text=@"℃";
        cell.unitLabel4.text=@"℃";
        cell.unitLabel5.text=@"A";
        cell.unitLabel6.text=@"A";
        cell.unitLabel7.text=NSLocalizedString(@"Min", nil);
        cell.unitLabel8.text=@"";
        cell.unitLabel9.text=@"";
        
        NSData *data;
        data=[self.dataDictionary objectForKey:@"Data4.7"]; //4.7 加热&冷凝参数读取
        if (data)
        {
            Byte*data_array=(Byte*)[data bytes];
            cell.valueTextfield1.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+0x0d*2]*256+data_array[3+0x0d*2+1]-400)/10.0f];
            cell.valueTextfield2.text=[NSString stringWithFormat:@"%.1f",(data_array[3+(0x0d+1)*2]*256+data_array[3+(0x0d+1)*2+1]-400)/10.0f];
            cell.valueTextfield3.text=[NSString stringWithFormat:@"%.1f",(data_array[3+(0x0d+2)*2]*256+data_array[3+(0x0d+2)*2+1]-400)/10.0f];
            cell.valueTextfield4.text=[NSString stringWithFormat:@"%.1f",(data_array[3+(0x0d+3)*2]*256+data_array[3+(0x0d+3)*2+1]-400)/10.0f];
            cell.valueTextfield5.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+(0x0d+4)*2]*256+data_array[3+(0x0d+4)*2+1])/10.0f];
            cell.valueTextfield6.text=[NSString stringWithFormat:@"%.1f",(float)(data_array[3+(0x0d+5)*2]*256+data_array[3+(0x0d+5)*2+1])/10.f];
            cell.valueTextfield7.text=[NSString stringWithFormat:@"%i",data_array[3+(0x0d+6)*2]*256+data_array[3+(0x0d+6)*2+1]];
//            cell.valueTextfield8.text=[NSString stringWithFormat:@"%i", (data_array[3+(0x0d+7)*2]*256+data_array[3+(0x0d+7)*2+1])];
//            cell.valueTextfield9.text=[NSString stringWithFormat:@"%i",data_array[3+(0x0d+8)*2]*256+data_array[3+(0x0d+8)*2+1]];
        }
        return cell;
    }
 
 
        if (balanceMode>0)
        {
            [cell.modeSwitch setOn:true];
        }
        else
        {
            [cell.modeSwitch setOn:false];
        }
        cell.titleLabel.text=Localized(@"Balancing function");
        cell.titleLabel1.text=Localized(@"Bal_OpenV");
        cell.titleLabel2.text=Localized(@"Bal_OpenD");
        cell.titleLabel3.text=Localized(@"Bal_CloseD");
        cell.titleLabel4.text=Localized(@"Bal_CloseD2");
        cell.titleLabel5.text=Localized(@"Bal_TimeOdd");
        cell.titleLabel6.text=Localized(@"Bal_TimeEven");
        cell.titleLabel7.text=Localized(@"Bal_TimeMos");
        cell.titleLabel8.text=Localized(@"Reserve");
        cell.titleLabel9.text=@"";
    
    
        cell.unitLabel1.text=@"mv";
        cell.unitLabel2.text=@"mv";
        cell.unitLabel3.text=@"mv";
        cell.unitLabel4.text=@"mv";
        cell.unitLabel5.text=Localized(@"Seconds");
        cell.unitLabel6.text=Localized(@"Seconds");
        cell.unitLabel7.text=Localized(@"Seconds");
        cell.unitLabel8.text=@"";
        cell.unitLabel9.text=@"";
    
    NSData *data;
    data=[self.dataDictionary objectForKey:@"Data4.2"]; //4.2 均衡参数读取
    if (data)
    {
        Byte*data_array=(Byte*)[data bytes];
        cell.valueTextfield1.text=[NSString stringWithFormat:@"%i",data_array[3]*256+data_array[3+1]];
        cell.valueTextfield2.text=[NSString stringWithFormat:@"%i",data_array[3+2]*256+data_array[3+2+1]];
        cell.valueTextfield3.text=[NSString stringWithFormat:@"%i",data_array[3+2*2]*256+data_array[3+2*2+1]];
        cell.valueTextfield4.text=[NSString stringWithFormat:@"%i",data_array[3+3*2]*256+data_array[3+3*2+1]];
        cell.valueTextfield5.text=[NSString stringWithFormat:@"%i",data_array[3+4*2]*256+data_array[3+4*2+1]];
        cell.valueTextfield6.text=[NSString stringWithFormat:@"%i",data_array[3+5*2]*256+data_array[3+5*2+1]];
        cell.valueTextfield7.text=[NSString stringWithFormat:@"%i",data_array[3+6*2]*256+data_array[3+6*2+1]];

    }
        return cell;
    
 
    return cell;
    
}

-(UITableViewCell*) getSafteyCell:(NSIndexPath *)indexPath
{
    NSString *firstTitle = Localized(@"First level_OV_Cell");
    NSString *secondTitle = Localized(@"Second level_OV_Cell");
    NSString *thirdTitle = Localized(@"Third level_OV_Cell");
    NSString *recoveryTitle = Localized(@"Recovery volt_OV_Cell");
    NSString *delayTitle = Localized(@"Delay time_OV_Cell");
    if (indexPath.section == 6) {
        firstTitle = Localized(@"First level_UV_Cell");
        secondTitle = Localized(@"Second level_UV_Cell");
        thirdTitle = Localized(@"Third level_UV_Cell");
        recoveryTitle = Localized(@"Recovery volt_UV_Cell");
        delayTitle = Localized(@"Delay time_UV_Cell");
    }else if (indexPath.section == 7) {
        firstTitle = Localized(@"First level_OV_Bat");
        secondTitle = Localized(@"Second level_OV_Bat");
        thirdTitle = Localized(@"Third level_OV_Bat");
        recoveryTitle = Localized(@"Recovery volt_OV_Bat");
        delayTitle = Localized(@"Delay time_OV_Bat");
    }else if (indexPath.section == 8) {
        firstTitle = Localized(@"First level_UV_Bat");
        secondTitle = Localized(@"Second level_UV_Bat");
        thirdTitle = Localized(@"Third level_UV_Bat");
        recoveryTitle = Localized(@"Recovery volt_UV_Bat");
        delayTitle = Localized(@"Delay time_UV_Bat");
    }else if (indexPath.section == 9) {
        firstTitle = Localized(@"First level_OC_CHG");
        secondTitle = Localized(@"Second level_OC_CHG");
        thirdTitle = Localized(@"Third level_OC_CHG");
        recoveryTitle = Localized(@"Recovery volt_OC_CHG");
        delayTitle = Localized(@"Delay time_OC_CHG");
    }else if (indexPath.section == 10) {
        firstTitle = Localized(@"First level_OC_DSG");
        secondTitle = Localized(@"Second level_OC_DSG");
        thirdTitle = Localized(@"Third level_OC_DSG");
        recoveryTitle = Localized(@"Recovery volt_OC_DSG");
        delayTitle = Localized(@"Delay time_OC_DSG");
    }else if (indexPath.section == 11) {
        firstTitle = Localized(@"First level_OT_CHG");
        secondTitle = Localized(@"Second level_OT_CHG");
        thirdTitle = Localized(@"Third level_OT_CHG");
        recoveryTitle = Localized(@"Recovery temp_OT_CHG");
        delayTitle = Localized(@"Delay time_OT_CHG");
    }else if (indexPath.section == 12) {
        firstTitle = Localized(@"First level_UT_CHG");
        secondTitle = Localized(@"Second level_UT_CHG");
        thirdTitle = Localized(@"Third level_UT_CHG");
        recoveryTitle = Localized(@"Recovery temp_UT_CHG");
        delayTitle = Localized(@"Delay time_UT_CHG");
    }else if (indexPath.section == 13) {
        firstTitle = Localized(@"First level_OT_DSG");
        secondTitle = Localized(@"Second level_OT_DSG");
        thirdTitle = Localized(@"Third level_OT_DSG");
        recoveryTitle = Localized(@"Recovery temp_OT_DSG");
        delayTitle = Localized(@"Delay time_OT_DSG");
    }else if (indexPath.section == 14) {
        firstTitle = Localized(@"First level_UT_DSG");
        secondTitle = Localized(@"Second level_UT_DSG");
        thirdTitle = Localized(@"Third level_UT_DSG");
        recoveryTitle = Localized(@"Recovery temp_UT_DSG");
        delayTitle = Localized(@"Delay time_UT_DSG");
    }else if (indexPath.section == 15) {
        firstTitle = Localized(@"First level_OT_MOS");
        secondTitle = Localized(@"Second level_OT_MOS");
        thirdTitle = Localized(@"Third level_OT_MOS");
        recoveryTitle = Localized(@"Recovery temp_OT_MOS");
        delayTitle = Localized(@"Delay time_OT_MOS");
    }else if (indexPath.section == 16) {
        firstTitle = Localized(@"First level_VDifference");
        secondTitle = Localized(@"Second level_VDifference");
        thirdTitle = Localized(@"Third level_VDifference");
        recoveryTitle = Localized(@"Recovery VDifference");
        delayTitle = Localized(@"Delay time VDifference");
    }else if (indexPath.section == 17) {
        firstTitle = Localized(@"First level Low SOC");
        secondTitle = Localized(@"Second level Low SOC");
        thirdTitle = Localized(@"Third level Low SOC");
        recoveryTitle = Localized(@"Recovery Low SOC");
        delayTitle = Localized(@"Delay time Low SOC");
    }
    SafetySettingTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"SafetySettingTableViewCell" forIndexPath:indexPath];
    cell.titleLabelOne.text             = firstTitle;
    cell.titleLabelTwo.text             = secondTitle;
    cell.titleLabelThree.text           = thirdTitle;
    cell.titleLabelRestore.text         = recoveryTitle;
    cell.titleLabelDelay.text           = delayTitle;
    cell.syncButton.tag                 = indexPath.section-5;
    if (indexPath.section==5) //单节过压
    {
    cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][0]];
    cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][1]];
    cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][2]];
    cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][3]];
    cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
    
    cell.unitLabelOne.text              = @"mV";
    cell.unitLabelTwo.text              = @"mV";
    cell.unitLabelThree.text            = @"mV";
    cell.unitLabelRestore.text          = @"mV";
    cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==6) //单节低压
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][0]];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][1]];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][2]];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][3]];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"mV";
        cell.unitLabelTwo.text              = @"mV";
        cell.unitLabelThree.text            = @"mV";
        cell.unitLabelRestore.text          = @"mV";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==7) //总压过压
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][0])/100.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][1])/100.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][2])/100.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][3])/100.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"V";
        cell.unitLabelTwo.text              = @"V";
        cell.unitLabelThree.text            = @"V";
        cell.unitLabelRestore.text          = @"V";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==8) //总压低压
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][0])/100.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][1])/100.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][2])/100.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.2f",(float)(SafetySetting[indexPath.section-5][3])/100.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"V";
        cell.unitLabelTwo.text              = @"V";
        cell.unitLabelThree.text            = @"V";
        cell.unitLabelRestore.text          = @"V";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==9) //充电过流
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][0])/10.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][1])/10.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][2])/10.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][3])/10.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"A";
        cell.unitLabelTwo.text              = @"A";
        cell.unitLabelThree.text            = @"A";
        cell.unitLabelRestore.text          = @"A";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==10) //放电过流
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][0])/10.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][1])/10.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][2])/10.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][3])/10.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"A";
        cell.unitLabelTwo.text              = @"A";
        cell.unitLabelThree.text            = @"A";
        cell.unitLabelRestore.text          = @"A";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==11) //充电过温
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][0]-400)/10.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][1]-400)/10.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][2]-400)/10.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][3]-400)/10.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"°C";
        cell.unitLabelTwo.text              = @"°C";
        cell.unitLabelThree.text            = @"°C";
        cell.unitLabelRestore.text          = @"°C";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==12) //充电低温
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][0]-400)/10.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][1]-400)/10.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][2]-400)/10.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][3]-400)/10.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"°C";
        cell.unitLabelTwo.text              = @"°C";
        cell.unitLabelThree.text            = @"°C";
        cell.unitLabelRestore.text          = @"°C";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==13) //放电过温
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][0]-400)/10.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][1]-400)/10.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][2]-400)/10.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][3]-400)/10.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"°C";
        cell.unitLabelTwo.text              = @"°C";
        cell.unitLabelThree.text            = @"°C";
        cell.unitLabelRestore.text          = @"°C";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==14) //放电低温
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][0]-400)/10.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][1]-400)/10.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][2]-400)/10.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][3]-400)/10.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"°C";
        cell.unitLabelTwo.text              = @"°C";
        cell.unitLabelThree.text            = @"°C";
        cell.unitLabelRestore.text          = @"°C";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==15) //MOS过温
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][0]-400)/10.0f];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][1]-400)/10.0f];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][2]-400)/10.0f];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.1f",(float)(SafetySetting[indexPath.section-5][3]-400)/10.0f];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"°C";
        cell.unitLabelTwo.text              = @"°C";
        cell.unitLabelThree.text            = @"°C";
        cell.unitLabelRestore.text          = @"°C";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==16) //压差过大
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%.0f",(float)SafetySetting[indexPath.section-5][0]];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%.0f",(float)SafetySetting[indexPath.section-5][1]];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%.0f",(float)SafetySetting[indexPath.section-5][2]];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%.0f",(float)SafetySetting[indexPath.section-5][3]];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"mV";
        cell.unitLabelTwo.text              = @"mV";
        cell.unitLabelThree.text            = @"mV";
        cell.unitLabelRestore.text          = @"mV";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (indexPath.section==17) //电量过低
    {
        cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][0]];
        cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][1]];
        cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][2]];
        cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][3]];
        cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",SafetySetting[indexPath.section-5][4]];
        
        cell.unitLabelOne.text              = @"%";
        cell.unitLabelTwo.text              = @"%";
        cell.unitLabelThree.text            = @"%";
        cell.unitLabelRestore.text          = @"%";
        cell.unitLabelDelay.text            = @"10ms";
    }
    if (self.isReadSafteyData==false)
    {
        [cell.syncButton setHidden:true];
    }
    else
    {
        [cell.syncButton setHidden:false];
    }
    [cell.syncButton addTarget:self action:@selector(safetySyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
    return cell;

}


-(UITableViewCell*) getShortProtectionCell:(NSIndexPath *)indexPath
{
    NSString *sectionTitle;
    sectionTitle=_sectionArray[indexPath.section];
    ShortProtectionTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ShortProtectionTableViewCell" forIndexPath:indexPath];
    cell.titleLabelOne.text             = [NSString stringWithFormat:@"%@",Localized(@"C-CHG-Ref") ];
    cell.titleLabelTwo.text             = [NSString stringWithFormat:@"%@",Localized(@"C-DSG-Ref")];
    cell.titleLabelThree.text           = [NSString stringWithFormat:@"%@",Localized(@"Cs-Ref")];
    cell.titleLabelRestore.text         = [NSString stringWithFormat:@"%@",Localized(@"Cs-Delay_time") ];
    cell.titleLabelDelay.text           = [NSString stringWithFormat:@"%@",Localized(@"SOC_TableSel")];
    cell.PermanentPasswordLabel.text    = [NSString stringWithFormat:@"%@",Localized(@"PassW_Forever")];
    cell.LabelReserveLabel.text    = [NSString stringWithFormat:@"%@",Localized(@"C-limit_VDifference")];
    cell.LabelReserveLabel2.text    = [NSString stringWithFormat:@"%@",Localized(@"C-limit_Cur")];
    
    cell.valueTextfieldOne.text         = [NSString stringWithFormat:@"%i",chargeRefrenceCurrent];
    cell.valueTextfieldTwo.text         = [NSString stringWithFormat:@"%i",dischargeRefenceCurrent];
    cell.valueTextfieldThree.text       = [NSString stringWithFormat:@"%i",chargeShortCurrent];
    cell.valueTextfieldRestore.text     = [NSString stringWithFormat:@"%i",dischargeShortCurrent];
    cell.valueTextfieldDelay.text       = [NSString stringWithFormat:@"%i",onetimePassword];
    cell.valueTextfieldPermantPassword.text       = [NSString stringWithFormat:@"%i",permanentPassword];
    cell.valueTextfieldReserve.text       = [NSString stringWithFormat:@"%i",shortReserve];
    cell.valueTextfieldReserve2.text       = [NSString stringWithFormat:@"%i",shortReserve2];
    cell.unitLabelOne.text              = @"A";
    cell.unitLabelTwo.text              = @"A";
    cell.unitLabelThree.text            = @"A";
    cell.unitLabelRestore.text          = @"us";
    cell.unitLabelDelay.text            = @"";
    cell.unitLabelPermanentPasswordLabel.text=@"";
    cell.unitLabelReserveLabel.text=@"mV";
    cell.unitLabelReserveLabel2.text=@"A";
    cell.unitLabelDelay.text=@"";
    [cell.syncButton addTarget:self action:@selector(shortSyncBtn:)  forControlEvents:UIControlEventTouchUpInside];
    return cell;

}

-(void)shortSyncBtn:(UIButton*)syncBtn
{
        long basicIndex;
        basicIndex=syncBtn.tag;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"Confirm") message:Localized(@"Are you sure you want to write to the device?") preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Confirm") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            ShortProtectionTableViewCell *cell;
            cell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:18]];
            long d1,d2,d3,d4,d5,d6,d7,d8,d9,d10;
            d1=cell.valueTextfieldOne.text.integerValue;
            d2=cell.valueTextfieldTwo.text.integerValue;
            d3=cell.valueTextfieldThree.text.integerValue;
            d4=cell.valueTextfieldRestore.text.integerValue;
            d5=cell.valueTextfieldDelay.text.integerValue;
            d6=cell.valueTextfieldPermantPassword.text.integerValue;
            d7=cell.valueTextfieldReserve.text.integerValue;
            d8=cell.valueTextfieldReserve2.text.integerValue;
 
            Byte write_array[25];
            write_array[0] = 0x01;//
            write_array[1] = 0x10;//
            write_array[2] = 0x23;//
            write_array[3] = 0x08;//
            write_array[4] = 0x00;//
            write_array[5] = 0x8;//
            write_array[6] = 0x10;//

            write_array[7] = [self getHighByte:d1*10];
            write_array[8] = [self getLowByte:d1*10];
            write_array[9] = [self getHighByte:d2*10];
            write_array[10] = [self getLowByte:d2*10];
            write_array[11] = [self getHighByte:d3*10];
            write_array[12] = [self getLowByte:d3*10];
            write_array[13] = [self getHighByte:d4*10];
            write_array[14] = [self getLowByte:d4*10];
            write_array[15] = [self getHighByte:d5];
            write_array[16] = [self getLowByte:d5];
            write_array[17] = [self getHighByte:d6];
            write_array[18] = [self getLowByte:d6];
            write_array[19] = [self getHighByte:d7];
            write_array[20] = [self getLowByte:d7];
            write_array[21] = [self getHighByte:d8];
            write_array[22] = [self getLowByte:d8];
            write_array[23]=0x00;
            write_array[24]=0x00;
            [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:25];
            [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Cancel") style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:true completion:nil];
        
    
}

-(void)mosrelaySwitchChange:(UISwitch*)switchButton
{
        BOOL onOff;
        onOff=switchButton.isOn;
        [self turnOnOffFunction:0x55  OnoffType:onOff];
}

-(void)switchChange:(UISwitch*)switchButton
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"Confirm") message:Localized(@"Are you sure you want to write to the device?") preferredStyle:UIAlertControllerStyleAlert];
 
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Confirm") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BOOL onOff;
        onOff=switchButton.isOn;
        [self turnOnOffFunction:switchButton.tag OnoffType:onOff];
     
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Cancel") style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

-(void)queryHeatAndCool //4.7 加热&冷凝参数读取
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x23;//
    write_array[3] = 0x20;//
    write_array[4] = 0x00;//
    write_array[5] = 0x18;//
    write_array[6] = 0x4f;//
    write_array[7] = 0x8e;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}


-(void)querySaftey //4.1 保护参数读取
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x21;//
    write_array[3] = 0x00;//
    write_array[4] = 0x00;//
    write_array[5] = 0x41;//
    write_array[6] = 0x8f;//
    write_array[7] = 0xc6;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)querySoc //4.5 SOC参数读取
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x23;//
    write_array[3] = 0x18;//
    write_array[4] = 0x00;//
    write_array[5] = 0x4;//
    write_array[6] = 0xcf;//
    write_array[7] = 0x8a;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)queryBasicInfo //4.6 系统基础参数读取
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x23;//
    write_array[3] = 0x1c;//
    write_array[4] = 0x00;//
    write_array[5] = 0x4;//
    write_array[6] = 0x8e;//
    write_array[7] = 0x4b;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)queryBatteryAndOtherInfo //3.4 主控读取电池其他信息
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0xd1;//
    write_array[3] = 0x15;//
    write_array[4] = 0x00;//
    write_array[5] = 0xc;//
    write_array[6] = 0x6d;//
    write_array[7] = 0x37;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)querySleepInfo //4.4 休眠参数读取
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x23;//
    write_array[3] = 0x10;//
    write_array[4] = 0x00;//
    write_array[5] = 0x08;//
    write_array[6] = 0x4e;//
    write_array[7] = 0x4d;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)queryBalanceInfo//4.2 均衡参数读取
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x23;//
    write_array[3] = 0x00;//
    write_array[4] = 0x00;//
    write_array[5] = 0x08;//
    write_array[6] = 0x4f;//
    write_array[7] = 0x88;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)queryProtection//4.3 保护参数
{
    //010323080008ce4a
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x23;//
    write_array[3] = 0x08;//
    write_array[4] = 0x00;//
    write_array[5] = 0x08;//
    write_array[6] = 0xce;//
    write_array[7] = 0x4a;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

#pragma mark - recive data
-(void)didUpdateData:(NSNotification*)noti {
    NSData *Notidata;
    Notidata=noti.object;
    Byte *dataBytes = (Byte*)Notidata.bytes;
    for (int t = 0; t < Notidata.length; t++) {
        dataBytes[t] = dataBytes[t] & 0xff;
    }
    if (Notidata.length < 2) {
        return;
    }
    NSLog(@"didUpdateData : %ld=>%@", self.queryOrder, Notidata);

    if (dataBytes[2]==0x82) { // 4.1 保护参数读取
//        self.queryOrder = 4;
        [self.quryResultStatus replaceObjectAtIndex:3 withObject:@1];
        for (int t=0;t<13;t++) {
            for (int j=0;j<5;j++) {
                int value;
                value=dataBytes[3+t*10+j*2]*256+dataBytes[3+t*10+j*2+1];
                SafetySetting[t][j]=value;
            }
        }
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data4.1"];
        if (self.isReadSafteyData==false) {
            self.isReadSafteyData=true;
            if (!self.userIsEditing) {
                [self.tableView reloadData];
            }
        }
        return;
    }
    if (dataBytes[2]==0x18) { //3.4 主控读取电池其他信息
//        self.queryOrder = 2;
        [self.quryResultStatus replaceObjectAtIndex:1 withObject:@1];
        int modeInfo,batteryInfo,funcitonInfo;
        batteryInfo= dataBytes[3]*256+dataBytes[3+1];
        modeInfo= dataBytes[3+2*2]*256+dataBytes[3+2*2+1];
        funcitonInfo=dataBytes[3+2*2+1]*256+dataBytes[3+2*2];
        //funcitonInfo=34306;
        sleepMode=modeInfo&0x200;
        balanceMode=modeInfo&0x8000;
        coolMode=modeInfo&0x40;
        heatMode=modeInfo&0x20;
        mosRelayMode=funcitonInfo&0x400;
        //[_titleLabel setText: [NSString stringWithFormat:@"%@",Notidata]];
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data3.4"];
        if (!self.userIsEditing) {
            [self.tableView reloadData];
        }
        return;
    }
    if (dataBytes[2]==0x30) {  //4.7 加热&冷凝参数读取
//        self.queryOrder = 5;
        [self.quryResultStatus replaceObjectAtIndex:4 withObject:@1];
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data4.7"];
        if (!self.userIsEditing) {
            [self.tableView reloadData];
        }
        return;
    }
    if  (dataBytes[2]==0x10 && self.queryOrder == 6) {    //4.4 休眠参数读取
//        self.queryOrder = 6;
        [self.quryResultStatus replaceObjectAtIndex:5 withObject:@1];
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data4.4"];
        if (!self.userIsEditing) {
            [self.tableView reloadData];
        }
        return;
    }
    if (dataBytes[2]==0x10 && self.queryOrder == 7) { //4.2 均衡参数读取
//        self.queryOrder = 7;
        [self.quryResultStatus replaceObjectAtIndex:6 withObject:@1];
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data4.2"];
        if (!self.userIsEditing) {
            [self.tableView reloadData];
        }
        return;
    }
    if (dataBytes[2]==0x10 && self.queryOrder == 8) { //4.3 保护参数读取
//        self.queryOrder = 0;
        [self.quryResultStatus replaceObjectAtIndex:7 withObject:@1];
        chargeRefrenceCurrent=( dataBytes[3]*256+dataBytes[3+1])/10;
        dischargeRefenceCurrent=( dataBytes[3+2]*256+dataBytes[3+2+1])/10;
        chargeShortCurrent= (dataBytes[3+2*2]*256+dataBytes[3+2*2+1])/10;
        dischargeShortCurrent= (dataBytes[3+3*2]*256+dataBytes[3+3*2+1])/10;
        onetimePassword= dataBytes[3+4*2]*256+dataBytes[3+4*2+1];
        permanentPassword=dataBytes[3+5*2]*256+dataBytes[3+5*2+1];
        shortReserve=dataBytes[3+6*2]*256+dataBytes[3+6*2+1];
        shortReserve2=dataBytes[3+7*2]*256+dataBytes[3+7*2+1];
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data4.3"];
        if (!self.userIsEditing) {
            [self.tableView reloadData];
        }
        return;
    }
    if (dataBytes[2]==0x8 && self.queryOrder == 3) {  //4.5 SOC参数读取
//        self.queryOrder = 3;
        NSLog(@"didUpdate value : 3=>%@",Notidata);
        [self.quryResultStatus replaceObjectAtIndex:2 withObject:@1];
        batteryCapacity= (dataBytes[3]*256+dataBytes[4])/10.0;
        loopCount=dataBytes[5]*256+dataBytes[6];
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data4.5"];
        if (!self.userIsEditing) {
            [self.tableView reloadData];
        }
        return;
    }
    if (dataBytes[2]==0x8 && self.queryOrder == 1) {  //4.6 系统基础参数读取
//        self.queryOrder = 1;
        NSLog(@"didUpdate value : 1=>%@",Notidata);
        [self.quryResultStatus replaceObjectAtIndex:0 withObject:@1];
        serialCount= dataBytes[3]*256+dataBytes[4];
        resistanceValue=dataBytes[5]*256+dataBytes[6];
        resistanceCount=dataBytes[7]*256+dataBytes[8];
        preChargeDischargeTime=dataBytes[9]*256+dataBytes[10];
        
        [self.dataDictionary setObject:[Notidata copy]  forKey:@"Data4.6"];
        if (!self.userIsEditing) {
            [self.tableView reloadData];
        }
        return;
    }
    
    if ((dataBytes[1]==0x10) ||   (dataBytes[1]==0x06))//设置成功
    {
//        for (NSInteger i=0; i<self.quryResultStatus.count; i++) {
//            self.quryResultStatus[i] = @0;
//        }
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(@"Parameter setting succeeded", nil) preferredStyle:UIAlertControllerStyleAlert];
        [alter addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:nil]];
        return;
    }
    if ((dataBytes[1]==0x90) ||   (dataBytes[1]==0x86))//设置失败
    {
        for (NSInteger i=0; i<self.quryResultStatus.count; i++) {
            self.quryResultStatus[i] = @0;
        }
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(@"Parameter setting failed", nil) preferredStyle:UIAlertControllerStyleAlert];
        [alter addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:nil]];
        return;
    }
}

-(void)turnOnOffFunction:(int) commandType OnoffType:(BOOL)onOffType
{
   
    int onOffValue;
    int commandValue=0;
    onOffValue=0x02;
    if(commandType==0x01) commandValue=0x0a;//休眠
    if(commandType==0x02) commandValue=0x06;//加热
    if(commandType==0x03) commandValue=0x07;//冷凝
    if(commandType==0x04) commandValue=0x01;//均衡
    if(commandType==0x055) commandValue=0x03;//均衡
    if (onOffType==0) onOffValue=0x03;
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x06;//
    write_array[2] = 0x11;//
    write_array[3] = onOffValue;//
    write_array[4] = 0x00;//
    write_array[5] = commandValue;//
    write_array[6] = 0x00;//
    write_array[7] = 0x00;//
    [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:8];
    [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
    //01061103 000afcf1 <01061102 000aad31> <01061102 0001ecf6>
    /*
    NSData *data;
    data=[dataDictionary objectForKey:@"Data3.4"]; //3.4 主控读取电池其他信息
    if (data)
    {
        int length;
        Byte*data_array=(Byte*)[data bytes];
        length=0x07+24*2+0x02;
        Byte write_array[length];
        write_array[0] = 0x01;//
        write_array[1] = 0x10;//
        write_array[2] = 0xd1;//
        write_array[3] = 0x15;//
        write_array[4] = 0x00;//
        write_array[5] = 24;//
        write_array[6] = 24*2;//
        
        for (int t=0;t<48;t++)
        {
            write_array[7+t]=data_array[t+3];
        }
 
        NSData *tempData;
        tempData=[NSData dataWithBytes:write_array length:length];
        NSLog(@"write data:%@",tempData);
        [_manager SendCommandWithCrc:write_array Length:length];
    }
     */
}


-(void)FunctionSyncBtn :(UIButton *)syncBtn
{
    long basicIndex;
    basicIndex=syncBtn.tag;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"Confirm") message:Localized(@"Are you sure you want to write to the device?") preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Confirm") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        FunctionOnOffTableViewCell *cell;
        cell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:basicIndex]];
        long d1,d2,d3,d4,d5,d6,d7,d8,d9,d10;
        d1=cell.valueTextfield1.text.integerValue;
        d2=cell.valueTextfield2.text.integerValue;
        d3=cell.valueTextfield3.text.integerValue;
        d4=cell.valueTextfield4.text.integerValue;
        d5=cell.valueTextfield5.text.integerValue;
        d6=cell.valueTextfield6.text.integerValue;
        d7=cell.valueTextfield7.text.integerValue;
        d8=cell.valueTextfield8.text.integerValue;
        d9=cell.valueTextfield9.text.integerValue;
        d10=cell.valueTextfield10.text.integerValue;
        if (basicIndex==1) //休眠功能
        {
            d5 = d5 * 10;
            d6 = d6 * 10;
            NSData *data;
            data=[self.dataDictionary objectForKey:@"Data4.4"]; //4.4 休眠参数读取
            if (data)
            {
                int length;
                Byte*data_array=(Byte*)[data bytes];
                //<01031013 88003c03 e8003c00 1e001e00 f000005f>
                length=0x07+0x08*2+0x02;
                Byte write_array[length];
                write_array[0] = 0x01;//
                write_array[1] = 0x10;//
                write_array[2] = 0x23;//
                write_array[3] = 0x10;//
                write_array[4] = 0x00;//
                write_array[5] = 0x8;//
                write_array[6] = 0x8*2;//
                
                for (int t=0;t<16;t++)
                {
                    write_array[7+t]=data_array[t+3];
                }
                write_array[7] = [self getHighByte:d1];
                write_array[8] = [self getLowByte:d1];
                write_array[9] = [self getHighByte:d2];
                write_array[10] = [self getLowByte:d2];
                write_array[11] = [self getHighByte:d3];
                write_array[12] = [self getLowByte:d3];
                write_array[13] = [self getHighByte:d4];
                write_array[14] = [self getLowByte:d4];
                write_array[15] = [self getHighByte:d5];
                write_array[16] = [self getLowByte:d5];
                write_array[17] = [self getHighByte:d6];
                write_array[18] = [self getLowByte:d6];
                write_array[19] = [self getHighByte:d7];
                write_array[20] = [self getLowByte:d7];
                
                
                NSData *tempData;
                tempData=[NSData dataWithBytes:write_array length:length];
               
                NSLog(@"sync:%@",@"同步休眠数据");
                [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
                [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
            }
        }
        
        if (basicIndex==2) //加热功能
        {
            
            NSData *data;
            data=[self.dataDictionary objectForKey:@"Data4.7"]; //4.7 加热&冷凝参数读取
            if (data)
            {
                int length;
                Byte*data_array=(Byte*)[data bytes];
                length=0x07+24*2+0x02;
                Byte write_array[length];
                write_array[0] = 0x01;//
                write_array[1] = 0x10;//
                write_array[2] = 0x23;//
                write_array[3] = 0x20;//
                write_array[4] = 0x00;//
                write_array[5] = 24;//
                write_array[6] = 48;//
                
                for (int t=0;t<48;t++)
                {
                    write_array[7+t]=data_array[t+3];
                }
                d1=d1*10+400;
                d2=d2*10+400;
                d3=d3*10+400;
                d4=d4*10+400;
                d5=d5*10+400;
                d6=d6*10+400;
                d7=d7*10;
                d8=d8*10;
                write_array[7] = [self getHighByte:d1];
                write_array[8] = [self getLowByte:d1];
                write_array[9] = [self getHighByte:d2];
                write_array[10] = [self getLowByte:d2];
                write_array[11] = [self getHighByte:d3];
                write_array[12] = [self getLowByte:d3];
                write_array[13] = [self getHighByte:d4];
                write_array[14] = [self getLowByte:d4];
                write_array[15] = [self getHighByte:d5];
                write_array[16] = [self getLowByte:d5];
                write_array[17] = [self getHighByte:d6];
                write_array[18] = [self getLowByte:d6];
                write_array[19] = [self getHighByte:d7];
                write_array[20] = [self getLowByte:d7];
                write_array[21] = [self getHighByte:d8];
                write_array[22] = [self getLowByte:d8];
                write_array[23] = [self getHighByte:d9];
                write_array[24] = [self getLowByte:d9];
            
                
                NSData *tempData;
                tempData=[NSData dataWithBytes:write_array length:length];
                NSLog(@"sync:%@",@"同步加热数据");
                [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
                [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
            }
        }
        if (basicIndex==3) //冷凝功能
        {
            NSData *data;
            data=[self.dataDictionary objectForKey:@"Data4.7"]; //4.7 加热&冷凝参数读取
            if (data)
            {
                int length;
                Byte*data_array=(Byte*)[data bytes];
                length=0x07+24*2+0x02;
                Byte write_array[length];
                write_array[0] = 0x01;//
                write_array[1] = 0x10;//
                write_array[2] = 0x23;//
                write_array[3] = 0x20;//
                write_array[4] = 0x00;//
                write_array[5] = 24;//
                write_array[6] = 48;//
                
                for (int t=0;t<48;t++)
                {
                    write_array[7+t]=data_array[t+3];
                }
                d1=d1*10+400;
                d2=d2*10+400;
                d3=d3*10+400;
                d4=d4*10+400;
                d5=d5*10;
                d6=d6*10;
                write_array[7+13*2] = [self getHighByte:d1];
                write_array[8+13*2] = [self getLowByte:d1];
                write_array[9+13*2] = [self getHighByte:d2];
                write_array[10+13*2] = [self getLowByte:d2];
                write_array[11+13*2] = [self getHighByte:d3];
                write_array[12+13*2] = [self getLowByte:d3];
                write_array[13+13*2] = [self getHighByte:d4];
                write_array[14+13*2] = [self getLowByte:d4];
                write_array[15+13*2] = [self getHighByte:d5];
                write_array[16+13*2] = [self getLowByte:d5];
                write_array[17+13*2] = [self getHighByte:d6];
                write_array[18+13*2] = [self getLowByte:d6];
                write_array[19+13*2] = [self getHighByte:d7];
                write_array[20+13*2] = [self getLowByte:d7];
                
                
                NSData *tempData;
                tempData=[NSData dataWithBytes:write_array length:length];
           
                NSLog(@"sync:%@",@"同步冷凝数据");
                [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
                [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
            }
        }
        
        if (basicIndex==4) //均衡功能
        {
            NSData *data;
            data=[self.dataDictionary objectForKey:@"Data4.2"]; //4.2 均衡参数读取
            if (data)
            {
                int length;
                Byte*data_array=(Byte*)[data bytes];
                length=0x07+0x8*2+0x02;
                Byte write_array[length];
                write_array[0] = 0x01;//
                write_array[1] = 0x10;//
                write_array[2] = 0x23;//
                write_array[3] = 0x00;//
                write_array[4] = 0x00;//
                write_array[5] = 0x8;//
                write_array[6] = 0x8*2;//
                
                for (int t=0;t<16;t++)
                {
                    write_array[7+t]=data_array[t+3];
                }
                write_array[7] = [self getHighByte:d1];
                write_array[8] = [self getLowByte:d1];
                write_array[9] = [self getHighByte:d2];
                write_array[10] = [self getLowByte:d2];
                write_array[11] = [self getHighByte:d3];
                write_array[12] = [self getLowByte:d3];
                write_array[13] = [self getHighByte:d4];
                write_array[14] = [self getLowByte:d4];
                write_array[15] = [self getHighByte:d5];
                write_array[16] = [self getLowByte:d5];
                write_array[17] = [self getHighByte:d6];
                write_array[18] = [self getLowByte:d6];
                write_array[19] = [self getHighByte:d7];
                write_array[20] = [self getLowByte:d7];
                //d2无法更新???
                
                NSData *tempData;
                tempData=[NSData dataWithBytes:write_array length:length];
             
                NSLog(@"sync:%@",@"同步均衡数据");
                [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
                [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
            }
        }
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Cancel") style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:true completion:nil];
    
}

-(void)basicSyncBtn :(UIButton *)syncBtn
{
    long basicIndex;
    basicIndex=syncBtn.tag;
    EditTableViewCell *cell;
    cell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:basicIndex inSection:0]];
    long value;
    value=cell.valueTextfield.text.integerValue;
    NSLog(@"sync value=%li",value);
    if (basicIndex==2) //串数
    {
        [self syncBytes:0x23
             addressLow:0x1c
              ValueHigh:[self getHighByte:value]
               ValueLow:[self getLowByte:value]];
    }
    if (basicIndex==3) //电池包容量
    {
        NSInteger value = (NSInteger)(cell.valueTextfield.text.doubleValue*10);
        [self syncBytes:0x23
             addressLow:0x18
              ValueHigh:[self getHighByte:value]
               ValueLow:[self getLowByte:value]];
    }
    if (basicIndex==4) //循环次数
    {
        [self syncBytes:0x23
             addressLow:0x19
              ValueHigh:[self getHighByte:value]
               ValueLow:[self getLowByte:value]];
    }
    if (basicIndex==5) //预充时间
    {
        [self syncBytes:0x23
             addressLow:0x1f
              ValueHigh:[self getHighByte:value]
               ValueLow:[self getLowByte:value]];
    }
    if (basicIndex==6) //采样电阻阻值
    {
        [self syncBytes:0x23
             addressLow:0x1d
              ValueHigh:[self getHighByte:value]
               ValueLow:[self getLowByte:value]];
    }
    if (basicIndex==7) //采样电阻数量
    {
        [self syncBytes:0x23
             addressLow:0x1e
              ValueHigh:[self getHighByte:value]
               ValueLow:[self getLowByte:value]];
    }
}

-(void)safetySyncBtn :(UIButton *)syncBtn
{
    
    long safetyMode;
    safetyMode=syncBtn.tag;
    SafetySettingTableViewCell *cell;
    cell=[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:safetyMode+5]];
    long safetyLevelOneValue,safetyLevelTwoValue,safetyLevelThirdValue,safetyLevelRestoreValue,safetyLevelDelayValue;
    safetyLevelOneValue=cell.valueTextfieldOne.text.integerValue;
    safetyLevelTwoValue=cell.valueTextfieldTwo.text.integerValue;
    safetyLevelThirdValue=cell.valueTextfieldThree.text.integerValue;
    safetyLevelRestoreValue=cell.valueTextfieldRestore.text.integerValue;
    safetyLevelDelayValue=cell.valueTextfieldDelay.text.integerValue;

        
    if (safetyMode==0) //单节过压
    {
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if (safetyMode==1) //单节低压
    {
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if (safetyMode==2) //总压过压
    {
        safetyLevelOneValue=safetyLevelOneValue*100;
        safetyLevelTwoValue=safetyLevelTwoValue*100;
        safetyLevelThirdValue=safetyLevelThirdValue*100;
        safetyLevelRestoreValue=safetyLevelRestoreValue*100;
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if (safetyMode==3) //总压低压
    {
        safetyLevelOneValue=safetyLevelOneValue*100;
        safetyLevelTwoValue=safetyLevelTwoValue*100;
        safetyLevelThirdValue=safetyLevelThirdValue*100;
        safetyLevelRestoreValue=safetyLevelRestoreValue*100;
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if (safetyMode==4) //充电过流
    {
        safetyLevelOneValue=safetyLevelOneValue*10;
        safetyLevelTwoValue=safetyLevelTwoValue*10;
        safetyLevelThirdValue=safetyLevelThirdValue*10;
        safetyLevelRestoreValue=safetyLevelRestoreValue*10;
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if (safetyMode==5) //放电过流
    {
        safetyLevelOneValue=safetyLevelOneValue*10;
        safetyLevelTwoValue=safetyLevelTwoValue*10;
        safetyLevelThirdValue=safetyLevelThirdValue*10;
        safetyLevelRestoreValue=safetyLevelRestoreValue*10;
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if ((safetyMode==6)||(safetyMode==7) ||(safetyMode==8)||(safetyMode==9)||(safetyMode==10)) //充电过温 充电过温 放电过温  放电低温 MOS过温
    {
        safetyLevelOneValue=safetyLevelOneValue*10+400;
        safetyLevelTwoValue=safetyLevelTwoValue*10+400;
        safetyLevelThirdValue=safetyLevelThirdValue*10+400;
        safetyLevelRestoreValue=safetyLevelRestoreValue*10+400;
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if (safetyMode==11) //压差过大
    {
       // safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    if (safetyMode==12) //电量过低
    {
        //safetyLevelDelayValue=safetyLevelDelayValue*100;
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"Confirm") message:Localized(@"Are you sure you want to write to the device?") preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Confirm") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    NSData *data;
    data=[self.dataDictionary objectForKey:@"Data4.1"]; //4.1 保护参数读取
    if (data)
    {
        int length;
        //Byte*data_array=(Byte*)[data bytes];
        length=0x07+0x5*2+0x02;
 
        Byte write_array[length];
        write_array[0] = 0x01;//
        write_array[1] = 0x10;//
        write_array[2] = 0x21;//
        write_array[3] = safetyMode*5;//
        write_array[4] = 0x00;//
        write_array[5] = 0x5;//
        write_array[6] = 0x5*2;//
        
//        for (int t=0;t<0x5*2;t++)
//        {
//            write_array[7+t]=data_array[t+3+5*safetyMode];
//        }
        write_array[7 ]  = [self getHighByte: safetyLevelOneValue];
        write_array[8 ]  = [self getLowByte: safetyLevelOneValue];
        write_array[9 ]  = [self getHighByte: safetyLevelTwoValue];
        write_array[10 ] = [self getLowByte: safetyLevelTwoValue];
        write_array[11 ] = [self getHighByte: safetyLevelThirdValue];
        write_array[12 ] = [self getLowByte: safetyLevelThirdValue];
        write_array[13 ] = [self getHighByte: safetyLevelRestoreValue];
        write_array[14 ] = [self getLowByte: safetyLevelRestoreValue];
        write_array[15 ] = [self getHighByte: safetyLevelDelayValue];
        write_array[16 ] = [self getLowByte: safetyLevelDelayValue];
 

        NSLog(@"sync:%@",@"同步保护数据");

        [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
        [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
        //01102100 0040809f 0b0b0b36 36000064 640b220b 220af00b b800640b 7c0b7c0b 9f0b3600 6407cb07 cb07a808 34006400 c8012c01 f403e800 6404b005 dc070803 e8006404 b004b004 b0047e00 64019a01 9a019a01 c2006404 b004b004 b0047e00 64019a01 9a019a01 c2006404 b004b004 b0047e00 64012c01 2c01f401 2c006400 0a000500 010005fa 1a
    }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Cancel") style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)syncBytes:(int)addressHigh addressLow:(int)addressLow ValueHigh:(int)valueHigh ValueLow:(int)valueLow
{
    if ((addressLow>=0x1c) && (addressLow<=0x1F)&& (addressHigh==0x23))
    {
        NSData *data;
        data=[self.dataDictionary objectForKey:@"Data4.6"]; //4.6 系统基础参数读取
        if (data)
        {
            int length;
            Byte*data_array=(Byte*)[data bytes];
            length=0x07+0x08+0x02;
            Byte write_array[length];
            write_array[0] = 0x01;//
            write_array[1] = 0x10;//
            write_array[2] = 0x23;//
            write_array[3] = 0x1c;//
            write_array[4] = 0x00;//
            write_array[5] = 0x4;//
            write_array[6] = 0x8;//
     
            for (int t=0;t<8;t++)
            {
                write_array[7+t]=data_array[t+3];
            }
            write_array[7+(addressLow-0x1c)*2]=valueHigh;
            write_array[7+(addressLow-0x1c)*2+1]=valueLow;
            NSData *tempData;
            tempData=[NSData dataWithBytes:write_array length:length];
             
            NSLog(@"write data:%@",tempData);
            [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
            [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
        }
        return ;
    }

    if ((addressLow>=0x18) && (addressLow<=0x1B)&& (addressHigh==0x23))
    {
        NSData *data;
        data=[self.dataDictionary objectForKey:@"Data4.5"]; //4.5 SOC参数读取
        if (data)
        {
            
            int length;
            Byte*data_array=(Byte*)[data bytes];
            length=0x07+0x08+0x02;
            Byte write_array[length];
            write_array[0] = 0x01;//
            write_array[1] = 0x10;//
            write_array[2] = 0x23;//
            write_array[3] = 0x18;//
            write_array[4] = 0x00;//
            write_array[5] = 0x4;//
            write_array[6] = 0x8;//
            
            for (int t=0;t<8;t++)
            {
                write_array[7+t]=data_array[t+3];
            }
            write_array[7+(addressLow-0x18)*2]=valueHigh;
            write_array[7+(addressLow-0x18)*2+1]=valueLow;
            NSData *tempData;
            tempData=[NSData dataWithBytes:write_array length:length];
            NSLog(@"write data:%@",tempData);
            [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
            [self performSelector:@selector(refetchData) withObject:nil afterDelay:1];
        }
    }
//    Byte write_array[13];
//    write_array[0] = 0x01;//
//    write_array[1] = 0x10;//
//    write_array[2] = addressHigh;//
//    write_array[3] = addressLow;//
//    write_array[4] = 0x00;//
//    write_array[5] = 0x2;//
//    write_array[6] = 0x4;//
//    write_array[7] = valueHigh;//
//    write_array[8] = valueLow;//
//    write_array[9] = valueHigh;//
//    write_array[10] = valueLow;//
//    write_array[11] = 0x00;//
//    write_array[12] = 0x00;//
//
//    [_manager sendCommandWithCrc:write_array Length:13];
    
}

-(void)clearData
{
//    for (int t=0;t<13;t++)
//    {
//        for (int j=0;j<5;j++)
//        {
//
//            SafetySetting[t][j]=0;
//        }
//    }
//    batteryCapacity=0;
//    loopCount=0;
//    fillTime=0;
//    resistanceCount=0;
//    resistanceValue=0;//采样电阻
//    preChargeDischargeTime=0;//预充时间
//    serialCount=0;//串数
//    sleepMode=0;//休眠功能状态
//    balanceMode=0;//均衡功能
//    heatMode=0;//加热功能
//    coolMode=0;//冷凝功能
//    mosRelayMode=0;//mosrelay
//    [_isExpandArray removeAllObjects];
//    for (NSInteger i = 0; i < _sectionArray.count; i++) {
//        [_isExpandArray addObject:@"0"];//0:没展开 1:展开
//    }
}

-(int)getHighByte:(long)value
{
    return (int)value/256;
}

-(int)getLowByte:(long)value
{
    return (int)(value-(value/256)*256);
}

-(void)refetchData
{
    [self refresh];
//    [ProgressHUD showActivityMessageInWindow:Localized(@"Retrieve setting...") timer:15];
//    queryOrder=0;
}
@end
